﻿using System;
using System.Linq;
using System.Text;
using Kaidou.Model;
using System.Data;
using System.Data.SqlClient;
using Kaidou.Util;
using System.Collections;
using Kaidou.Persister;
using System.Collections.Generic;
using Kaidou.Model;
using System.Text.RegularExpressions;

/**
 * 受注見出、明細のManager
 */
namespace Kaidou.Bll
{
    public class TRN_JuchuManager
    {
        /**
	     * 受注見出を登録する
	     */
        public void insertOrder(Order order, System.Resources.ResourceManager rm, LoginModel loginModel, string RootPath)
        {
            String order_no = null;
            int order_seal_qty = 0;
            int report_seal_qty = 0;
            float report_rate = 0.00f;
            SqlDB db = new SqlDB();

            try
            {
                db.TransBegin();
                LogManager.info("TRN_JuchuManager insertOrder - begin");
                //パーシスターを作成
                TRN_Juchu_HPersister per_H = new TRN_Juchu_HPersister();
                TRN_Juchu_DPersister per_D = new TRN_Juchu_DPersister();
                //TRN_Purch_SealPersister per_S = new TRN_Purch_SealPersister();
                MST_UnionPersister per_Union = new MST_UnionPersister();
                TRN_Report_Rate_Persister per_RP = new TRN_Report_Rate_Persister();

                //order_noを取得
                order_no = per_H.makeJuchuNo();
                //***** insert JUCHU_H *****//

                //過去年分の報告率を取得
                ArrayList list = per_RP.getReportRates(loginModel.Unioncode);

                for (int i = 0; i < list.Count; i++)
                {
                    TrnReportRate cal_model = (TrnReportRate)list[i];
                    //購入枚数を合計
                    order_seal_qty = order_seal_qty + cal_model.OrderSealQty;
                    //報告枚数を合計する
                    report_seal_qty = report_seal_qty + cal_model.ReportSealQty;
                }

                //累計報告率の計算
                if (report_seal_qty != 0)
                {
                    report_rate = ((float)report_seal_qty / (float)order_seal_qty) * 100;
                }

                //報告率セット
                //order.getJuchu_H().ReportRate = float.Parse(report_rate.ToString("#.##"));
                order.getJuchu_H().ReportRate = report_rate;
                int standardrate = int.Parse(rm.GetString("kaidou_forceorder_rate"));

                if (standardrate > report_rate)
                {
                    order.getJuchu_H().ForcedJuchuFlg = TrnJuchuh.FORCED_JUCHU_FLAG_FORCED;
                    //組合員の制限解除フラグを通常に戻す
                    MstUnion union = new MstUnion();
                    MstUnionId id = new MstUnionId();
                    id.UnionCode = order.getJuchu_H().UnionCode;
                    union.Id = id;
                    union.UpdDate = System.DateTime.Now;
                    union.UpdUnionCode = loginModel.Unioncode;
                    union.UpdBranchCode = (short)loginModel.Branchcode;
                    union.UpdFuncId = "insertOrder()";
                    union.CancelRestFlg = MstUnion.CANCEL_REST_FLG_NORMAL;
                    //組合員をアップデート
                    per_Union.updateUnionCanselResetFlag(db, union);

                }
                else
                {
                    order.getJuchu_H().ForcedJuchuFlg = TrnJuchuh.FORCED_JUCHU_FLAG_NORMAL;
                }

                //order_noをセット
                order.getJuchu_H().JuchuNo = order_no;

                //発注区分セット
                order.getJuchu_H().JuchuClss = TrnJuchuh.JUCHU_CLSS_INTERNET;


                //Timestampをセット
                //ord.getJuchu_H().setJuchu_date(ts);
                order.getJuchu_H().RegDate = System.DateTime.Now;

                //発注者
                order.getJuchu_H().UnionCode = loginModel.Unioncode;
                order.getJuchu_H().BranchCode = (short)loginModel.Branchcode;

                order.getJuchu_H().JuchuDate = System.DateTime.Now;
                //order.getJuchu_H().FaxRcvDate = System.DateTime.Now;
                //order.getJuchu_H().HachuDate = System.DateTime.Now;
                //order.getJuchu_H().DelivDate = System.DateTime.Now;
                //Update 情報セット
                order.getJuchu_H().UpdDate = System.DateTime.Now;
                order.getJuchu_H().UpdUnionCode = loginModel.Unioncode;
                order.getJuchu_H().UpdBranchCode = (short)loginModel.Branchcode;

                if (TrnJuchuh.JUCHU_CLSS_INTERNET.Equals(order.getJuchu_H().JuchuClss))
                {
                    order.getJuchu_H().UpdFuncId = "insertOrder()";
                }
                else if (TrnJuchuh.JUCHU_CLSS_FAX.Equals(order.getJuchu_H().JuchuClss))
                {
                    order.getJuchu_H().UpdFuncId = "prosessFaxocrData";
                }
                else
                {
                    order.getJuchu_H().UpdFuncId = "insertOrder()";
                }

                //ステータスをセット
                order.getJuchu_H().JuchuSts = TrnJuchuh.JUCHU_STATUS_NOTORDERD;

                //FAX/OCRエラーフラグをセット
                order.getJuchu_H().FaxErrorFlg = TrnJuchuh.FAX_ERROR_FLAG_OK;

                //合計枚数をセット
                order.getJuchu_H().TotalSealQty = order.getTotal_seal_qty();

                //insert
                per_H.juchu_HInsert(db, order.getJuchu_H());

                //***** insert JUCHU_D *****//

                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        if (order.getJuchu_D()[i] == null)
                            continue;
                        if (order.getJuchu_D()[i].SealQty == 0)
                            continue;
                    }
                    catch (Exception exx)
                    {
                        break;
                    }
                    order.getJuchu_D()[i].Id.JuchuNo = order_no;
                    order.getJuchu_D()[i].RegDate = System.DateTime.Now;
                    order.getJuchu_D()[i].UpdDate = System.DateTime.Now;

                    order.getJuchu_D()[i].UpdUnionCode = loginModel.Unioncode;
                    order.getJuchu_D()[i].UpdBranchCode = (short)loginModel.Branchcode;
                    if (TrnJuchuh.JUCHU_CLSS_INTERNET.Equals(order.getJuchu_H().JuchuClss))
                    {
                        order.getJuchu_D()[i].UpdFuncId = "insertReport()";
                    }
                    else if (TrnJuchuh.JUCHU_CLSS_FAX.Equals(order.getJuchu_H().JuchuClss))
                    {
                        order.getJuchu_D()[i].UpdFuncId = "prosessFaxocrData";
                    }
                    else
                    {
                        order.getJuchu_D()[i].UpdFuncId = "insertReport()";
                    }


                    per_D.insert(db, order.getJuchu_D()[i]);

                    // trn_report_seal
                    // ここでは未発注のため、シールは発番しない。
                    //per_S.insertByProcedure(con,ord.getJuchu_D()[i]);
                }


                //注文メール送信
                string reportBody = TemplateManager.getOrder(order, loginModel);
                Mail mail = new Mail();
                if (StringUtil.isEmpty(loginModel.OfficeEmail))
                {
                    //メールアドレスが無いので、プロパティ参照
                    LogManager.info("TRN_JuchuManager  mail setTo:" + rm.GetString("kaidou_mailsend_default_to"));
                    mail.setTo(rm.GetString("kaidou_mailsend_default_to"));
                }
                else
                {
                    //メール送信
                    LogManager.info("TRN_JuchuManager ---------- mail setTo:" + loginModel.OfficeEmail);
                    mail.setTo(loginModel.OfficeEmail);
                }
                LogManager.info("TRN_JuchuManager  ---------- mail to end");
                string bcc = rm.GetString("kaidou_mailsend_bcc");
                if (bcc != null && !StringUtil.isEmpty(bcc))
                {
                    mail.setBcc(bcc);
                }

                mail.setSubject("[回胴遊商]ご注文受け付けました。");
                mail.setMessage(reportBody);

                MailSendManager.sendMail(mail, RootPath);


                db.TransCommit();


            }
            catch (Exception pe)
            {
                //rollback
                db.TransRollback();
                LogManager.error("TRN_JuchuManager insertOrder - fail" + pe.Message + pe.StackTrace);
                throw new Exception("TRN_JuchuManager insertOrder - fail" + pe.Message + pe.StackTrace);

            }
            finally
            {
                db.Close();
            }

            

        }

        /**
	     * [代理注文]
	     * 受注見出を登録する.
	     * メールは飛ばさない
	     */
        public void insertOrder_Represen(Order order, System.Resources.ResourceManager rm, LoginModel loginModel)
        {
            String order_no = null;
            int order_seal_qty = 0;
            int report_seal_qty = 0;
            float report_rate = 0.00f;
            SqlDB db = new SqlDB();

            try
            {
                db.TransBegin();
                LogManager.info("TRN_JuchuManager insertOrder_Represen - begin");
                //パーシスターを作成
                TRN_Juchu_HPersister per_H = new TRN_Juchu_HPersister();
                TRN_Juchu_DPersister per_D = new TRN_Juchu_DPersister();
                //TRN_Purch_SealPersister per_S = new TRN_Purch_SealPersister();
                MST_UnionPersister per_Union = new MST_UnionPersister();
                TRN_Report_Rate_Persister per_RP = new TRN_Report_Rate_Persister();

                //order_noを取得
                order_no = per_H.makeJuchuNo();
                //***** insert JUCHU_H *****//

                //過去2年分の報告率を取得
                ArrayList list = per_RP.getReportRates(order.getJuchu_H().UnionCode);

                for (int i = 0; i < list.Count; i++)
                {
                    TrnReportRate cal_model = (TrnReportRate)list[i];
                    //購入枚数を合計
                    order_seal_qty = order_seal_qty + cal_model.OrderSealQty;
                    //報告枚数を合計する
                    report_seal_qty = report_seal_qty + cal_model.ReportSealQty;
                }

                //累計報告率の計算
                if (report_seal_qty != 0)
                {
                    report_rate = ((float)report_seal_qty / (float)order_seal_qty) * 100;
                }

                //報告率セット
                //order.getJuchu_H().ReportRate = float.Parse(report_rate.ToString("#.##"));
                order.getJuchu_H().ReportRate = report_rate;
                int standardrate = int.Parse(rm.GetString("kaidou_forceorder_rate"));

                if (standardrate > report_rate)
                {
                    order.getJuchu_H().ForcedJuchuFlg = TrnJuchuh.FORCED_JUCHU_FLAG_FORCED;
                    //組合員の制限解除フラグを通常に戻す
                    MstUnion union = new MstUnion();
                    MstUnionId id = new MstUnionId();
                    id.UnionCode = order.getJuchu_H().UnionCode;
                    union.Id = id;
                    union.UpdDate = System.DateTime.Now;
                    union.UpdUnionCode = loginModel.Unioncode;
                    union.UpdBranchCode = (short)loginModel.Branchcode;
                    union.UpdFuncId = "insertOrder()";
                    union.CancelRestFlg = MstUnion.CANCEL_REST_FLG_NORMAL;
                    //組合員をアップデート
                    per_Union.updateUnionCanselResetFlag(db, union);

                }
                else
                {
                    order.getJuchu_H().ForcedJuchuFlg = TrnJuchuh.FORCED_JUCHU_FLAG_NORMAL;
                }

                //order_noをセット
                order.getJuchu_H().JuchuNo = order_no;

                //発注区分セット
                //order.getJuchu_H().JuchuClss = TrnJuchuh.JUCHU_CLSS_INTERNET;


                //Timestampをセット
                //ord.getJuchu_H().setJuchu_date(ts);
                order.getJuchu_H().RegDate = System.DateTime.Now;

                //発注者
                //order.getJuchu_H().UnionCode = loginModel.Unioncode;
                //order.getJuchu_H().BranchCode = (short)loginModel.Branchcode;

                //order.getJuchu_H().JuchuDate = System.DateTime.Now;
                //order.getJuchu_H().FaxRcvDate = System.DateTime.Now;
                //order.getJuchu_H().HachuDate = System.DateTime.Now;
                //order.getJuchu_H().DelivDate = System.DateTime.Now;
                //Update 情報セット
                order.getJuchu_H().UpdDate = System.DateTime.Now;
                order.getJuchu_H().UpdUnionCode = loginModel.Unioncode;
                order.getJuchu_H().UpdBranchCode = (short)loginModel.Branchcode;

                if (TrnJuchuh.JUCHU_CLSS_INTERNET.Equals(order.getJuchu_H().JuchuClss))
                {
                    order.getJuchu_H().UpdFuncId = "insertOrder()";
                }
                else if (TrnJuchuh.JUCHU_CLSS_FAX.Equals(order.getJuchu_H().JuchuClss))
                {
                    order.getJuchu_H().UpdFuncId = "prosessFaxocrData";
                }
                else
                {
                    order.getJuchu_H().UpdFuncId = "insertOrder()";
                }

                //ステータスをセット
                order.getJuchu_H().JuchuSts = TrnJuchuh.JUCHU_STATUS_NOTORDERD;

                //FAX/OCRエラーフラグをセット
                order.getJuchu_H().FaxErrorFlg = TrnJuchuh.FAX_ERROR_FLAG_OK;

                //合計枚数をセット
                order.getJuchu_H().TotalSealQty = order.getTotal_seal_qty();

                //insert
                per_H.juchu_HInsert(db, order.getJuchu_H());

                //***** insert JUCHU_D *****//

                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        if (order.getJuchu_D()[i] == null)
                            continue;
                        if (order.getJuchu_D()[i].SealQty == 0)
                            continue;
                    }
                    catch (Exception exx)
                    {
                        break;
                    }
                    order.getJuchu_D()[i].Id.JuchuNo = order_no;
                    order.getJuchu_D()[i].RegDate = System.DateTime.Now;
                    order.getJuchu_D()[i].UpdDate = System.DateTime.Now;

                    order.getJuchu_D()[i].UpdUnionCode = loginModel.Unioncode;
                    order.getJuchu_D()[i].UpdBranchCode = (short)loginModel.Branchcode;
                    if (TrnJuchuh.JUCHU_CLSS_INTERNET.Equals(order.getJuchu_H().JuchuClss))
                    {
                        order.getJuchu_D()[i].UpdFuncId = "insertReport()";
                    }
                    else if (TrnJuchuh.JUCHU_CLSS_FAX.Equals(order.getJuchu_H().JuchuClss))
                    {
                        order.getJuchu_D()[i].UpdFuncId = "prosessFaxocrData";
                    }
                    else
                    {
                        order.getJuchu_D()[i].UpdFuncId = "insertReport()";
                    }


                    per_D.insert(db, order.getJuchu_D()[i]);

                    // trn_report_seal
                    // ここでは未発注のため、シールは発番しない。
                    //per_S.insertByProcedure(con,ord.getJuchu_D()[i]);
                }

                db.TransCommit();

                LogManager.info("TRN_JuchuManager insertOrder_Represen - Committed");

            }
            catch (Exception pe)
            {
                //rollback
                db.TransRollback();
                LogManager.error("TRN_JuchuManager insertOrder_Represen - rollback" + pe.Message + pe.StackTrace);

            }
            finally
            {
                db.Close();
            }

            
        }
    	
        /**
	     * 注文を更新する（回胴User用）
	     * @param data データモデル
	     * @return boolean
	     */
	    public void updateOrderForKaidouUser(Order order,LoginModel loginModel) {

		    try {
			 
			    //パーシスターを作成
			    TRN_Juchu_HPersister perH = new TRN_Juchu_HPersister();
			    TRN_Juchu_DPersister perD = new TRN_Juchu_DPersister();

			    TrnJuchuh h = order.getJuchu_H();
			    TrnJuchud[] dlist = order.getJuchu_D();
			    TrnJuchud[] olddlist = perD.getDetail(h.JuchuNo);

                DateTime now=System.DateTime.Now;

			    h.FaxErrorFlg = TrnJuchuh.FAX_ERROR_FLAG_OK;
			    h.UpdDate = now;
			    h.UpdUnionCode = loginModel.Unioncode;
			    h.UpdBranchCode = (short)loginModel.Branchcode;
			    h.UpdFuncId = "updateOrderForKU" ;

			    //update
			    perH.updateJuchu_HForKaidouUser( new SqlDB(), h);

			    for (int i = 0; i < dlist.Length; i++) {
					    TrnJuchud d = dlist[i];

					    if (d == null) {
						    perD.delete( new SqlDB(), h.JuchuNo, i + 1);
					    } else {

						    d.UpdDate = now;
						    d.UpdUnionCode = loginModel.Unioncode;
			                d.UpdBranchCode = (short)loginModel.Branchcode;
						    d.UpdFuncId ="updateOrderForKU";

						    if (olddlist[i] != null) {
							     perD.update( new SqlDB(), d);
						    } else {
							    d.RegDate = now ;
							    perD.insert(new SqlDB(), d);
						    }
					    }
				 }

		    } catch (Exception pe) {
			   LogManager.error(" TRN_JuchuManager updateOrderForKaidouUser "+pe.Message+pe.StackTrace);
			   
		    } 

	    }

        /**
	     * 注文を更新する（回胴User用）
	     * @param data データモデル
	     * @return boolean
	     */
	    public void updateOrderedForKaidouUser(Order order,LoginModel loginModel)  {

            SqlDB db=new SqlDB();

            try
            {
                db.TransBegin();
                //パーシスターを作成
                TRN_Juchu_HPersister perH = new TRN_Juchu_HPersister();

                TrnJuchuh h = order.getJuchu_H();

                DateTime nowTimestamp = System.DateTime.Now;

                h.JuchuSts = TrnJuchuh.JUCHU_STATUS_DELIVERD;
                h.UpdDate = nowTimestamp;
                h.UpdUnionCode = loginModel.Unioncode;
                h.UpdBranchCode =(short) loginModel.Branchcode;
                h.UpdFuncId = "updateOrdered";
               

                //update
                 perH.updateJuchu_HForKaidouUser(db, h);

                db.TransCommit();
            }
            catch (Exception pe)
            {
                //rollback
                db.TransRollback();
                LogManager.error("TRN_JuchuManager updateOrdered " + pe.Message + pe.StackTrace);

            }
            finally
            {
                db.Close();
            }

	    }

        public List<string> checkInsertOrder(Order order, System.Resources.ResourceManager rm,LoginModel login)
        {
            InputErrorException ie = new InputErrorException(rm);

		    List<string> error1 = checkInsertJuchuH( order.getJuchu_H(),rm,login.Userclss );
		    List<string> error2 = checkInsertJuchuD( order.getJuchu_D(),rm );

		    ParameterCheckUtility.checkOrderQty(ie, order.getTotal_seal_qty(), order.getJuchu_H().OcrOrderQty);

		    order.getJuchu_H().TotalSealQty = order.getTotal_seal_qty( ) ;

		    string[] trader_no = order.getTrader_no();

		    ParameterCheckUtility.checkTraderNoDuplication(ie, trader_no);

		    //報告率をチェック
		    try {
                TRN_Report_Rate_Persister per_RP = new TRN_Report_Rate_Persister();
                int order_seal_qty = 0;
                int report_seal_qty =0;
                float report_rate = 0;
                //過去2年分の報告率を取得
                ArrayList list  = per_RP.getReportRates(login.Unioncode);
                for (int i = 0; i < list.Count; i++) {
                    TrnReportRate cal_model = (TrnReportRate) list[i];
                    //購入枚数を合計
                    order_seal_qty = order_seal_qty + cal_model.OrderSealQty;
                    //報告枚数を合計する
                    report_seal_qty = report_seal_qty + cal_model.ReportSealQty;
                }

                //累計報告率の計算
                if (report_seal_qty != 0) {
                  report_rate = ((float) report_seal_qty / (float) order_seal_qty) * 100;
                }

			    int standardrate = int.Parse(rm.GetString("kaidou_forceorder_rate"));

			    if (standardrate >= 0 && standardrate > report_rate) {
				    //報告率が基準値以下なので、組合員の制限解除フラグをチェックする
				    ParameterCheckUtility.checkUnionCancelResetFlag(ie,login.Unioncode);

			    }

		    } catch (Exception pe) {
			    LogManager.error("TRN_JuchuManager - checkInsertOrder "+pe.Message);
		    } 

		    
            List<string>  errorList = ie.getErrorMessages();
            errorList.AddRange(error1);
            errorList.AddRange(error2);

            return errorList;
        }

        public List<string> checkInsertJuchuH(TrnJuchuh juchu_h, System.Resources.ResourceManager rm,string login_user_clss)
        {
            InputErrorException ie = new InputErrorException(rm);

            //担当者名　if分追加
            if (login_user_clss.Equals("10"))
            {
                ParameterCheckUtility.checkJuchuTantoName(ie, juchu_h.JuchuTantoName);
            }

            //配達希望日
            ParameterCheckUtility.checkHopeDate(ie, juchu_h.HopeYear, juchu_h.HopeMonth, juchu_h.HopeDay);
            
            
            //FAXOCR枚数
            ParameterCheckUtility.checkOcrOrderQty(ie, juchu_h.OcrOrderQty);

            return ie.getErrorMessages();
        }

        public List<string> checkInsertJuchuD(TrnJuchud[] model, System.Resources.ResourceManager rm)
        {
            InputErrorException ie = new InputErrorException(rm);
		    TrnJuchud juchu_d = null;

		    //印字ありチェック
		    for (int i = 1; i < 5; i++) {
			    try {
				    juchu_d = model[i];
			    } catch (Exception exx) {
				    break;
			    }
			    if (juchu_d == null)
				    continue;

			    LogManager.info("TRN_JuchuManager checkInsertJuchuD check! : " + i);

			    try {
				    //シール枚数チェック
				    ParameterCheckUtility.checkSealQty(ie, juchu_d.SealQty);
				    //登録証番号チェック
				    ParameterCheckUtility.checkTraderRegNo(ie, juchu_d.TraderRegNo1, juchu_d.TraderRegNo2, juchu_d.SealQty);
				    //設置業者チェック
				    ParameterCheckUtility.existTrader(ie, juchu_d.TraderRegNo, juchu_d.TraderRegNo1, juchu_d.TraderRegNo2);

			    } catch (Exception pe) {
				    LogManager.error("TRN_JuchuManager checkInsertJuchuD"+pe.Message);
			    } 

			    if (juchu_d.SealQty == 0) {
				    model[i] = null;
			    }

		    }

		    //印字なしチェック
		    if (model[0] != null) {
			    LogManager.info("TRN_JuchuManager checkInsertJuchuD check! : " + 0);
			    //シール枚数チェック
			    ParameterCheckUtility.checkSealQty(ie, model[0].SealQty);
		    }

            return ie.getErrorMessages();
		   
        }

        /**
         * 確認シールのデータモデルの値がアプデイトに適していることを確認する
         * @param ord データモデル
         * @param ctx コンテキスト
         * @return Order データモデル
         */
        public List<string> checkUpdateOrder(Order order, System.Resources.ResourceManager rm, LoginModel login)
        {
            InputErrorException ie = new InputErrorException(rm);

            List<string> error1 = checkUpdateOrderH(order.getJuchu_H(), rm, login);
            
            //チェックはInsertと同じ
            List<string> error2=checkInsertJuchuD(order.getJuchu_D(),rm);


            ParameterCheckUtility.checkOrderQty(ie, order.getTotal_seal_qty(), order.getJuchu_H().OcrOrderQty);
            order.getJuchu_H().TotalSealQty = order.getTotal_seal_qty();

            string[] trader_no = order.getTrader_no();
            ParameterCheckUtility.checkTraderNoDuplication(ie, trader_no);

            List<string> error = ie.getErrorMessages();

            error.AddRange(error1);
            error.AddRange(error2);
           

            return error;
        }


        /**
         * 確認シールのデータモデルの値が正しいことを確認する
         * @param h データモデル
         * @param ctx コンテキスト
         * @return TRN_Juchu_H データモデル
         */
        public List<string> checkUpdateOrderH(TrnJuchuh h,System.Resources.ResourceManager rm,LoginModel login)  {
           
            InputErrorException ie = new InputErrorException(rm);

            
            try {
               //担当者名
                if (TrnJuchuh.JUCHU_CLSS_FAX.Equals(h.JuchuClss)) {
                    //FAX
                    if (!StringUtil.isEmpty(h.JuchuTantoName)) {
                        ParameterCheckUtility.checkJuchuTantoName(ie, h.JuchuTantoName);
                    }
                } else {
                    //Internet
                    if (login.Userclss.Equals("10")) {
                        ParameterCheckUtility.checkJuchuTantoName(ie, h.JuchuTantoName);
                    }
                }

                //受注日
                ParameterCheckUtility.checkJuchuDate(ie, h.JuchuYear, h.JuchuMonth, h.JuchuDay);
                //組合員コード
                ParameterCheckUtility.checkUnionCode(ie, h.UnionCode);
                //組合員コード存在チェック
                ParameterCheckUtility.existUnion( ie, h.UnionCode);
                //支店コード
                ParameterCheckUtility.checkBranchCode(ie, h.BranchCode);
                //支店コード存在チェック
                ParameterCheckUtility.existBranch(ie, h.UnionCode, h.BranchCode);

                //配達希望日
                ParameterCheckUtility.checkHopeDate(ie, h.HopeYear.ToString(), h.HopeMonth.ToString(), h.HopeDay.ToString());

                //FAXOCR枚数
                ParameterCheckUtility.checkOcrOrderQty(ie, h.OcrOrderQty);

            } catch (Exception pe) {
                LogManager.error("TRN_JuchuManager - checkUpdateOrderH "+pe.Message+pe.StackTrace);
               
            } 
            

            return ie.getErrorMessages();
        }
        
        /**
	     * 確認シールのデータモデルの値がアプデイトに適していることを確認する
	     * @param ord データモデル
	     * @return Order データモデル
	     */
        public List<string> checkUpdateOrdered(Order order, System.Resources.ResourceManager rm)
        {
		    InputErrorException ie = new InputErrorException(rm);

		    TrnJuchuh h = order.getJuchu_H();

		    //発送日
		    ParameterCheckUtility.checkDelivData(ie, h.DelivYear, h.DelivMonth, h.DelivDay);

		    //発送担当者
		    ParameterCheckUtility.checkDelivTantoName(ie, h.DelivTantoName);
		    //発送会社
		    ParameterCheckUtility.checkDelivCompName(ie, h.DelivCompName);
		    //伝票番号
		    ParameterCheckUtility.checkDelivNo(ie, h.DelivNo);


		    return ie.getErrorMessages();
	    }

        /**
	     * [代理注文]
	     * 代理注文の入力値チェック　その１.
	     * 区分・受信日・組合員コード・支店コード
	     */
        public List<string> checkInsertOrderRepresen1(string juchu_clss,string rcv_date_y,string rcv_date_m,string rcv_date_d,string union_code,string branch_code, System.Resources.ResourceManager rm)
        {
            /*
		     * 区分
		     * 　10 or 20
		     * 
		     * 受信日-年
		     * 　必須
		     * 受信日-月
		     * 　必須
		     * 受信日-日
		     * 　必須
		     * 受信日
		     * 　日付妥当性
		     * 
		     * 組合員コード
		     * 　必須
		     * 　マスタ存在
		     * 
		     * 支店コード
		     * 　必須
		     * 　マスタ存在
		     */
		    
		    InputErrorException ie = new InputErrorException(rm);

		    //#######################################################
		    // 区分　必須チェック
		    if (juchu_clss == null || "".Equals(juchu_clss)) {
			    // 4400=区分を入力してください。
			    ie.addErrorCode("E4400");
		    }
		    // 区分　値の妥当性チェック：FAX と インターネット 以外の場合はエラー
		    else if (!juchu_clss.Equals(TrnJuchuh.JUCHU_CLSS_FAX) && !juchu_clss.Equals(TrnJuchuh.JUCHU_CLSS_INTERNET)) {
			    // 4401=有効な区分を入力してください。
			    ie.addErrorCode("E4401");
		    }

		    //#######################################################
		    // 受信日チェック
		    bool dateYSafe = true;
		    bool dateMSafe = true;
		    bool dateDSafe = true;
		    // 受信日-年　必須チェック
		    if (rcv_date_y == null || "".Equals(rcv_date_y)) {
			    dateYSafe = false;
		    }
		    // 受信日-月　必須チェック
		    if (rcv_date_m == null || "".Equals(rcv_date_m)) {
			    dateMSafe = false;
		    }
		    // 受信日-日　必須チェック
		    if (rcv_date_d == null || "".Equals(rcv_date_d)) {
			    dateDSafe = false;
		    }
		    // 年月日のすべてが null or 空欄のとき
		    if (!dateYSafe && !dateMSafe && !dateDSafe) {
			    // 4410=受信日を入力してください。
			    ie.addErrorCode("E4410");
		    }
		    // 年月日のいずれか一つ以上に入力があるとき
		    else {
			    try {
				    // 数値 parse できない場合は NumberFormatException
				   /*
                    int y = int.Parse("20" + rcv_date_y);
				    int m = int.Parse(rcv_date_m);
				    int d = int.Parse(rcv_date_d);
				    int year=int.Parse(System.DateTime.Now.ToString("yyyy"));
                    int month=int.Parse(System.DateTime.Now.ToString("MM"));
                    int day=int.Parse(System.DateTime.Now.ToString("dd"));
                    */
				    // Calendar にセットした値と取得した値が等しくない場合
                    if (!StringUtil.isValidDate(rcv_date_y, rcv_date_m, rcv_date_d))
                    {
					    // 4411=有効な受信日を入力してください。
					    ie.addErrorCode("E4411");
				    }
			    } catch (Exception exx) {
				    // 4411=有効な受信日を入力してください。
				    ie.addErrorCode("E4411");
			    }
		    }
    		
		    // 組合員コード・支店コードの一括チェック（必須＋マスタ存在）
			ParameterCheckUtility.existUnionBranch( ie, union_code, branch_code);

            return ie.getErrorMessages();

        }
    
        /**
	     * [代理注文]
	     * 確認シールのデータモデルの値がインサートに適していることを確認する
	     * @return Order データモデル
	     */
        
	    public List<string> checkInsertOrder_Represen( Order order, System.Resources.ResourceManager rm ) {
		    
            InputErrorException ie = new InputErrorException(rm);

		    List<string> error1 = checkInsertJuchuH_Represen( order.getJuchu_H() , rm);


            List<string> error2 = checkInsertJuchuD(order.getJuchu_D(), rm);
		    
		    ParameterCheckUtility.checkOrderQty(ie, order.getTotal_seal_qty(),  order.getJuchu_H().OcrOrderQty);

		    order.getJuchu_H().TotalSealQty =order.getTotal_seal_qty();

		    string[] trader_no = order.getTrader_no();

		    ParameterCheckUtility.checkTraderNoDuplication(ie, trader_no);

            //報告率をチェック
		    try {
                TRN_Report_Rate_Persister per_RP = new TRN_Report_Rate_Persister();
                int order_seal_qty = 0;
                int report_seal_qty =0;
                float report_rate = 0;
                //過去2年分の報告率を取得
                ArrayList list  = per_RP.getReportRates(order.getJuchu_H().UnionCode);
                for (int i = 0; i < list.Count; i++) {
                    TrnReportRate cal_model = (TrnReportRate) list[i];
                    //購入枚数を合計
                    order_seal_qty = order_seal_qty + cal_model.OrderSealQty;
                    //報告枚数を合計する
                    report_seal_qty = report_seal_qty + cal_model.ReportSealQty;
                }

                //累計報告率の計算
                if (report_seal_qty != 0) {
                  report_rate = ((float) report_seal_qty / (float) order_seal_qty) * 100;
                }

			    int standardrate = int.Parse(rm.GetString("kaidou_forceorder_rate"));

			    if (standardrate >= 0 && standardrate > report_rate) {
				    //報告率が基準値以下なので、組合員の制限解除フラグをチェックする
                    ParameterCheckUtility.checkUnionCancelResetFlag(ie, order.getJuchu_H().UnionCode);

			    }

		    } catch (Exception pe) {
                LogManager.error("TRN_JuchuManager - checkInsertOrder_Represen " + pe.Message);
		    }

            List<string> error = ie.getErrorMessages();
            error.AddRange(error1);
            error.AddRange(error2);

            return error;
	    }


        /**
	     * [代理注文]
	     * 確認シールのデータモデルの値が正しいことを確認する
	     */
        public List<string> checkInsertJuchuH_Represen(TrnJuchuh juchu_h, System.Resources.ResourceManager rm)
        {
		    /*
		     * 受信日時-日付
		     * 　必須
		     * 　日付妥当性
		     * 
		     * 受信日時-時刻
		     * 　必須
		     * 　時刻妥当性
		     * 
		     * 注文日
		     * 　必須
		     * 　日付妥当性
		     * 
		     * 注文担当者
		     * 　入力は任意
		     * 
		     * 配達希望日
		     * 　（入力があるときのみ）
		     * 　日付妥当性
		     * 　注文日以降（注文日はOK）
		     */
            TrnJuchuh model = juchu_h;
		    InputErrorException ie = new InputErrorException(rm);

		    //受信日時-日付
            bool isValidReceiveDate = ParameterCheckUtility.checkReceiveDate(ie, model.FaxRcvYear, model.FaxRcvMonth, model.FaxRcvDay);
		    
		    //受信日時-時刻
            ParameterCheckUtility.checkRcvTime(ie, model.FaxRcvTime);

		    //注文日
            bool isValidOrderDate = ParameterCheckUtility.checkOrderDate(ie, model.JuchuYear, model.JuchuMonth, model.JuchuDay); 
		    
		    //担当者名
		    ParameterCheckUtility.checkJuchuTantoName_Represen(ie, model.JuchuTantoName);

		    //配達希望日
		    ParameterCheckUtility.checkHopeDate_Represen(ie, model.JuchuDate, isValidOrderDate, model.HopeYear, model.HopeMonth, model.HopeDay);
		    //FAXOCR枚数
		    ParameterCheckUtility.checkOcrOrderQty(ie, model.OcrOrderQty);

		    return ie.getErrorMessages();
	    }


        public List<string> checkOrderSearch(OrderSearchModel osm, System.Resources.ResourceManager rm)
        {
            InputErrorException ie = new InputErrorException(rm);
            if (!StringUtil.isEmpty(osm.getJuchu_str_date()))
            {
                if (!StringUtil.isNumber(osm.getJuchu_str_date()) )
                {
                    ie.addErrorCode("E9001");
                }

                if (osm.getJuchu_str_date().Length < 8)
                {
                    ie.addErrorCode("E9001");
                }
            }

            if (!StringUtil.isEmpty(osm.getJuchu_end_date()))
            {
                if (!StringUtil.isNumber(osm.getJuchu_end_date()) )
                {
                    ie.addErrorCode("E9001");
                }

                if (osm.getJuchu_end_date().Length < 8)
                {

                    ie.addErrorCode("E9001");
                }
            }

            if (osm.getReport_str_rate() != -1)
            {
                if (!StringUtil.isNumber(osm.getReport_str_rate().ToString()))
                {
                    ie.addErrorCode("E9002");
                }
            }

            if (osm.getReport_end_rate() != -1)
            {
                if (!StringUtil.isNumber(osm.getReport_end_rate().ToString()))
                {
                    ie.addErrorCode("E9002");
                }
            }


            if (osm.getJuchu_no() != null)
            {
                Regex r = new Regex(@"^[a-zA-Z]{1}\d{9}$");
                if (!r.IsMatch(osm.getJuchu_no()))
                {
                    ie.addErrorCode("E9003");
                }
               
            }
            return ie.getErrorMessages();
        }
       

    }
}
